package com.paddyi.controller;//package com.springcloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.paddyi.commons.http.HttpResult;
import com.paddyi.commons.qiniu.MyQiniu;
import com.paddyi.commons.utils.*;
import com.paddyi.model.SsoUser;
import com.paddyi.service.ISsoUserService;
import org.apache.http.protocol.HTTP;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 *
 * ClsTradeOrder 控制层
 *
 */
@RestController
public class LoginController extends BaseController{

    @Autowired
    ISsoUserService ssoUserService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

//    @RequestMapping("/ajaxLogin")
//    public HttpResult ajaxLogin() {
//        return HttpResult.error(401,"请登录!");
//    }

    /**
     * 登陆
     *
     * @param userInfo 用户
     */
    @PostMapping(value = "/login")
    public HttpResult login(@RequestBody SsoUser userInfo) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        String passWord = MD5.getMd5Str(userInfo.getPassword());
        System.out.println(passWord);
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getPhone(),passWord );
        try {
            // 执行认证登陆
            subject.login(token);
            SsoUser user = getCurrentUser();
            return HttpResult.ok(user);
        }catch (UnknownAccountException e) {
            return HttpResult.error(402,"账号不存在！");
        } catch (DisabledAccountException e) {
            return HttpResult.error(402,"账号未启用！");
        } catch (IncorrectCredentialsException e) {
            return HttpResult.error(402,"密码错误");
        } catch (ExcessiveAttemptsException e) {
            return HttpResult.error(402,"密码连续输错5次，停用半小时！");
        }
        catch (Throwable e) {
            return HttpResult.error(402,"未知错误，请联系管理员！");
        }
    }

    @GetMapping("/logout")
    public HttpResult logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return HttpResult.ok("退出登录成功");
    }

    @PostMapping(value="/regSendMsg")
    public HttpResult regSendMsg(@RequestBody SsoUser record) {

        if(StringUtils.isPhone(record.getPhone())){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("phone",record.getPhone());
            SsoUser ssoUser = ssoUserService.getOne(queryWrapper);
            if(ssoUser!=null){
                return HttpResult.error("手机号已经被注册，请更改后重试");
            }
            String redisCode = stringRedisTemplate.opsForValue().get(record.getPhone());
            if(StringUtils.isBlank(redisCode)){
                String code = RandomUtils.getRandom(6);
                String result = SendSmsUtil.SendSms(record.getPhone(),code);
                stringRedisTemplate.opsForValue().set(record.getPhone(),code,10,TimeUnit.MINUTES);
                return HttpResult.ok(code);
            }
            return HttpResult.error("获取验证码过于频繁，请稍后再试");
        }
        return HttpResult.error("手机号码填写有误！");
    }

    /**
     * 注册
     * @param record
     * @return
     */
    @PostMapping(value="/register")
    public HttpResult add(@RequestBody SsoUser record) {
        String code = stringRedisTemplate.opsForValue().get(record.getPhone());
        if(StringUtils.isBlank(code)){
            return HttpResult.error(406,"短信验证码过期,请重新注册!");
        }
        if(!code.equals(record.getVerNumber())){
            return HttpResult.error(406,"手机验证码错误!");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",record.getEmail());
        SsoUser user = ssoUserService.getOne(queryWrapper);
        if(user!=null){
          return HttpResult.error(406, "手机号码已被注册");
        }
        record.setStatus(0);
        record.setCreateTime(new Date());
        record.setPlaintext(record.getPassword());
        String MD5Password = MD5.getMd5Str(record.getPassword());
        record.setPassword(MD5Password);
        if(StringUtils.isBlank(record.getImg())){
            record.setImg("http://qiniu.paddyi.com/1560309450637.jpg?imageView2/1/w/200/h/200/q/75|imageslim");
        }
        ssoUserService.save(record);
        //静默登录
        UsernamePasswordToken token = new UsernamePasswordToken(record.getPhone(), MD5.getMd5Str(record.getPlaintext()));
        SecurityUtils.getSubject().login(token);
        return HttpResult.ok(getCurrentUser());
    }

    @GetMapping("/isLogin")
    public HttpResult isLogin() {
        Subject subject = SecurityUtils.getSubject();
        if(subject!=null){
            return HttpResult.ok("true");
        }
        return HttpResult.ok("false");
    }

    @PostMapping(value="/upimg")
    public HttpResult upimg(@RequestParam("file")MultipartFile file) {
        String date = new Date().getTime()+"";
        String fileName = file.getOriginalFilename();
        String[] fileNames = fileName.split("\\.");
        String type = fileNames[1];
        String name = date+"."+type;
        MyQiniu.uploadMultipartFile(file,name,true);
        return HttpResult.ok("http://qiniu.paddyi.com/"+name);
    }

}